from os.path import exists, join
from dataclasses import dataclass
from PySide2 import QtGui
from pandas import DataFrame

from PySide2.QtWidgets import QAbstractItemView, QTableWidget, QTableWidgetItem, QWidget, QHBoxLayout, QLineEdit, \
    QComboBox, QHeaderView, QPushButton, QTextEdit, QSizePolicy, QLabel
from PySide2.QtGui import QColor, QDesktopServices, QTextOption
from PySide2.QtCore import Qt, QUrl, QThread, Signal

from common.config import get_path


class Model_Combobox(QComboBox):
    def __init__(self):
        super().__init__()
        self.model = object()
        self.col_name = "new_attr"
        self.row_index = 0


class ButtonWithLink(QPushButton):
    def __init__(self, text, url):
        super().__init__(text)
        if url:
            if "http" in url:
                self.clicked.connect(lambda: open_url(url))
                return
            elif exists(url):
                self.clicked.connect(lambda: open_path(url))
                return
        self.setEnabled(False)

class ButtonFun(QPushButton):
    def __init__(self, text, func,func_para):
        super().__init__(text)
        if func:
            if func_para:
                self.clicked.connect(lambda: func(*func_para))
                return
            else:
                self.clicked.connect(lambda: func())
                return
        else:
            self.setEnabled(False)
    

# region common

# 设置单元个颜色
def set_item_color(wtb_item, color):
    """
    设置QtableWidget 单元格字体颜色
    """
    wtb_item.setForeground(QtGui.QBrush(QtGui.QColor(color)))


# 打开网址
def open_url(url):
    QDesktopServices.openUrl(QUrl(url))


# 打开文件或文件夹
def open_path(path):
    url = QUrl.fromLocalFile(path)
    QDesktopServices.openUrl(url)


# 设置Lable 的信息和颜色
def show_msg(txt, lb_msg: QLabel, color='blue'):
    if lb_msg:
        lb_msg.setVisible(True)
        lb_msg.setText(txt)
        lb_msg.setStyleSheet(f"color:{color}")
        # lb_msg.setWordWrap(True)  # 允许文本自动换行
        # lb_msg.adjustSize()


    # endregion


# region 向QTableWidget 添加各种控件

def btn_open_path(tb_view, path, cell, btn_name):
    widget_btn = QWidget()
    layout_btn = QHBoxLayout(widget_btn)
    btn_item = ButtonWithLink(btn_name, path)

    btn_item.setFixedSize(len(btn_name) * 20, 32)
    layout_btn.addWidget(btn_item)
    layout_btn.setContentsMargins(1, 1, 1, 1)
    tb_view.setCellWidget(*cell, widget_btn)


# endregion


class Th_Base(QThread):
    signal_send = Signal(object)
    signal_finished_signal = Signal(object)

    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        self.is_running = True

    def stop(self):
        self.is_running = False
        self.terminate()

    def on_thread_finished(self):
        self.deleteLater()
